#include <STC15F2K60S2.H>
#include "Nixie.h"
#include "Key.h"
#include "InitHC138.h"
#include "onewire.h"
#include "ultrasound.h"

float temper;
unsigned int length=50;
bit flag_l=0;
bit flag_t=0;
unsigned char Key_Val,Key_Old,Key_Up,Key_Down;
unsigned char flag4,flag5,flag6,flag7;
unsigned char num=0,num2=0;

//延时函数
void Delay(unsigned int x)	//@12.000MHz
{
	unsigned char data i, j;
while(x--)
{
	i = 12;
	j = 169;
	do
	{
		while (--j);
	} while (--i);
}
}
//定时器0
void Timer0_Init(void)		//1毫秒@12.000MHz
{
	AUXR &= 0x7F;			//定时器时钟12T模式
	TMOD &= 0xF0;			//设置定时器模式
	TL0 = 0x18;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
	TF0 = 0;				//清除TF0标志
	TR0 = 1;				//定时器0开始计时
	ET0 = 1;				//使能定时器0中断
	EA=1;
}
//实现按下S7增加限值，S6减少限值，S5确认限值，S4暂时没有用
void Key_Loop()
{
	Key_Val=ScanKey();
	Key_Down=Key_Val&(Key_Old^Key_Val);
	Key_Up=~Key_Val&(Key_Old^Key_Val);
	Key_Old=Key_Val;
	if(Key_Down==4)
	{
		flag4=1;
	}
	else if(Key_Down==5)
	{
		flag5=1;
	}
	else if(Key_Down==6)
	{
		flag6=1;
	}
	else if(Key_Down==7)
	{
		flag7=1;
	}
	
}
//温度显示
void temper_show()
{
		if(flag_t==1)
		{
		  temper=read_t();
			flag_t=0;
		}
		Nixie_SetBuf(6,(unsigned char)temper/10);
		Nixie_SetBuf(7,(unsigned char)temper%10);
		Nixie_SetBuf(8,(unsigned int)(temper*10)%10);
		point[7]=1;

}
void Beep(unsigned char flag)
{
	static unsigned char temp = 0x00;
	static unsigned char temp_old = 0xff;
	if(flag)
		temp |= 0x40;
	else
		temp &= ~0x40;
	if(temp != temp_old)
	{
		P0 = temp;
		InitHC138(5);
		temp_old = temp;		
	}	
}
void sys_init()
{
	P0 = 0xff;
	InitHC138(4);
	P0 = 0x00;
	InitHC138(5);
}


void main()
{
	Timer0_Init();
	sys_init();
	read_t();
	Delay(750);
	while(1)
	{
		if(flag_l==1)
		{
			flag_l=0;
			length=csb();
			Nixie_SetBuf(1,length/100);
			Nixie_SetBuf(2,length/10%10);
			Nixie_SetBuf(3,length%10);
		}
		if(length<num2)
		{
			Beep(1);
		}
		else
		{
			Beep(0);
		}
		if(temper<=40)
		{
			temper_show();
		}
		if(flag4==0)
		{
			if(num>0)
			{
				Nixie_SetBuf(1,num/10);
				Nixie_SetBuf(2,num%10);
			}
			else
			{
				Nixie_SetBuf(1,0);
				Nixie_SetBuf(2,0);
			}
		}

		if(num2>0)
		{
			Nixie_SetBuf(4,num2/10);
			Nixie_SetBuf(5,num2%10);
			
		}
	}
}

void Timer0_Isr(void) interrupt 1
{
	static unsigned char count1,count2,count4;
	static unsigned int count3;
	count1++;
	count2++;
	if(count1>=2)
	{
		Nixie_Loop();
		count1=0;
	}
	if(count2>=10)
	{
		count2=0;
		Key_Loop();
	}
	count4++;
	if(count4>=200&&flag4==1)
	{
		count4=0;
		flag_l=1;
//		flag4==0;
	}
		count3++;
	if(count3>=500)
	{
		count3=0;
		flag_t=1;
	}
	if(flag7==1)
	{
		num++;
		flag7=0;
	}
	if(flag6==1)
	{
		num--;
		flag6=0;
	}
	if(flag5==1)
	{
		num2=num;
		flag5=0;
		num=0;
	}
}
